package com.gwt.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Widget;
import com.gwt.client.PersonService;
import com.gwt.client.PersonServiceAsync;
import com.gwt.client.event.SlideTransitionEvent;
import com.gwt.shared.Person;

public class Slide9 extends Composite implements Slide{

	private static final Binder binder = GWT.create(Binder.class);

	interface Binder extends UiBinder<Widget, Slide9> {/***/}

	private final PersonServiceAsync personService = GWT.create(PersonService.class);
	
	private Slide.Presenter listener;
	private EventBus eventBus;
	
	@UiField FocusPanel slide;
	@UiField Button rpcRequestButton;
	@UiField DialogBox infoBox;
	@UiField HTMLPanel responseContent;

	public Slide9(EventBus eventBus) {
		this.eventBus = eventBus;
		initWidget(binder.createAndBindUi(this));
		
		infoBox.setVisible(false);
		infoBox.setAnimationEnabled(true);
		infoBox.setGlassEnabled(true);
	}
	
	@UiHandler("rpcRequestButton")
	public void handelRequest(ClickEvent e){
		personService.personServer(new AsyncCallback<Person>() {
			
			@Override
			public void onSuccess(Person result) {
				StringBuilder sb = new StringBuilder();
				sb.append("<b>Name: </b>" + result.getName() + "<br/>");
				sb.append("<b>Address: </b>" + result.getAddress() + "<br/>");
				sb.append("<b>Parent's Name: </b>" + result.getParent().getName() + "<br/>");
				sb.append("<b>Server Info: </b>" + result.getServerInfo() + "<br/>");
				sb.append("<b>Client Info: </b>" + result.getClientInfo() + "<br/>");
				
				infoBox.setWidget(new HTML(sb.toString()));
				infoBox.center();
			}
			
			@Override
			public void onFailure(Throwable caught) {
				Window.alert(caught.getMessage());
			}
		});
		
		Timer t = new Timer() {
			
			@Override
			public void run() {
				infoBox.hide();
			}
		};
		
		t.schedule(3000);
	}
	
	@Override
	protected void onLoad() {
		slide.setFocus(true);
	}
	
	@UiHandler("slide")
	public void keyPress(KeyDownEvent e){
		eventBus.fireEvent(new SlideTransitionEvent(e));
	}

	public void setPresenter(Slide.Presenter listener){
		this.listener = listener;
	}

}